package com.pzhuweb.sgblog.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.pzhuweb.sgblog.domain.dto.ArticleDto;
import com.pzhuweb.sgblog.domain.dto.CategoryDto;
import com.pzhuweb.sgblog.domain.dto.LinkDto;
import com.pzhuweb.sgblog.domain.dto.LinkStatusDto;
import com.pzhuweb.sgblog.domain.entity.Category;
import com.pzhuweb.sgblog.domain.entity.Link;
import com.pzhuweb.sgblog.domain.enums.AppHttpCodeEnum;
import com.pzhuweb.sgblog.domain.utils.BeanCopyUtils;
import com.pzhuweb.sgblog.domain.utils.ResponseResult;
import com.pzhuweb.sgblog.domain.utils.WebUtils;
import com.pzhuweb.sgblog.domain.vo.ArticleVo;
import com.pzhuweb.sgblog.domain.vo.ExcelCategoryVo;
import com.pzhuweb.sgblog.exception.SystemException;
import com.pzhuweb.sgblog.service.ArticleService;
import com.pzhuweb.sgblog.service.CategoryService;
import com.pzhuweb.sgblog.service.LinkService;
import com.pzhuweb.sgblog.service.TagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * @author 鄧浩奇
 * @classname ContentController
 * @description
 * @since 2023/8/16 16:45
 **/

@RestController
@RequestMapping("/content")
@Api(tags = "ContentController", description = "文章、分类、友链的增删改查")
public class ContentController {

    @Resource
    private CategoryService categoryService;

    @Resource
    private TagService tagService;

    @Resource
    private ArticleService articleService;

    @Resource
    private LinkService linkService;

    @ApiOperation(value = "查询所有分类")
    @GetMapping("/category/listAllCategory")
    public ResponseResult<?> listAllCategory() {
        return categoryService.listAllCategory();
    }

    @ApiOperation(value = "查询所有标签")
    @GetMapping("/tag/listAllTag")
    public ResponseResult<?> listAllTag() {
        return tagService.listAllTag();
    }


    /*
     * 新增文章
     * */
    @ApiOperation(value = "新增文章接口", notes = "新增文章")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "articleDto", value = "文章数据传输对象",dataTypeClass = Object.class)
    )
    @PostMapping("/article")
    public ResponseResult<?> writeArticle(@RequestBody ArticleDto articleDto) {
        if (!StringUtils.hasText(articleDto.getContent())) {
            throw new SystemException(AppHttpCodeEnum.LIST_IS_NULL);
        }
        if (!StringUtils.hasText(articleDto.getTitle())) {
            throw new SystemException(AppHttpCodeEnum.TITLE_IS_NULL);
        }
        if (!StringUtils.hasText(articleDto.getSummary())) {
            throw new SystemException(AppHttpCodeEnum.TITLE_IS_NULL);
        }
        return articleService.addArticle(articleDto);
    }

    /*
     * 获取文章列表
     * */
    @ApiOperation(value = "分页查询文章列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class,name = "pageNum", value = "页号",example = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小",dataTypeClass = Integer.class,example = "1"),
            @ApiImplicitParam(name = "title",value = "文章标题，用于模糊查询",dataTypeClass = String.class),
            @ApiImplicitParam(name = "summary",value = "文章摘要，用于模糊查询",dataTypeClass = String.class)
    })
    @GetMapping("/article/list")
    public ResponseResult<?> getArticleList(Integer pageNum, Integer pageSize, String title, String summary) {
        return articleService.getList(pageNum, pageSize, title, summary);
    }

    /*
     * 修改文章,获取需要修改的文章内容
     * */
    @ApiOperation(value = "根据文章id获取文章详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "文章id",dataTypeClass = Long.class,example = "1"),
    })
    @GetMapping("/article/{id}")
    public ResponseResult<?> getArticle(@PathVariable("id") Long id) {
        return articleService.getArticle(id);
    }

    /*
     * 修改文章
     * */
    @ApiOperation(value = "修改文章")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "articleVo", value = "待修改文章的信息",dataTypeClass = Object.class)
    })
    @PutMapping("/article")
    public ResponseResult<?> updateArticle(@RequestBody ArticleVo articleVo) {
        return articleService.updateArticle(articleVo);
    }

    /*
     * 删除文章
     * */
    @ApiOperation(value = "删除文章")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "需要删除的文章id集合",dataTypeClass = Collections.class,paramType = "path")
    })
    @DeleteMapping("/article/{id}")
    public ResponseResult<?> deleteArticleById(@PathVariable("id") List<Long> ids) {
        return articleService.deleteArticleByIds(ids);
    }

    /*
     * 分类分页查询
     * */
    @ApiOperation(value = "分页查询分类列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页号",dataTypeClass = Integer.class,example = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小",dataTypeClass = Integer.class,example = "1"),
            @ApiImplicitParam(name = "name",value = "分类名称",dataTypeClass = String.class),
            @ApiImplicitParam(name = "status",value = "分类状态",dataTypeClass = String.class)
    })
    @GetMapping("/category/list")
    public ResponseResult<?> getList(Integer pageNum, Integer pageSize, String name, String status) {
        return categoryService.getPageList(pageNum, pageSize, name, status);
    }

    /*
     * 新增分类
     * */
    @ApiOperation(value = "新增分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryDto", value = "分类数据传输对象",dataTypeClass = Object.class),
    })
    @PostMapping("/category")
    public ResponseResult<?> addCategory(@RequestBody CategoryDto categoryDto) {
        return categoryService.addCategory(categoryDto);
    }

    /*
     * 修改分类，获取待修改分类的信息
     * */
    @ApiOperation(value = "根据分类id获取分类详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "分类id",dataTypeClass = Long.class,example = "1",paramType = "path"),
    })
    @GetMapping("/category/{id}")
    public ResponseResult<?> getCategoryDetails(@PathVariable("id") Long id) {
        return categoryService.getDetails(id);
    }

    /*
     * 修改分类
     * */
    @ApiOperation(value = "修改分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryDto", value = "分类数据传输对象",dataTypeClass = Object.class),
    })
    @PutMapping("/category")
    public ResponseResult<?> updateCategory(@RequestBody CategoryDto categoryDto) {
        return categoryService.updateCategory(categoryDto);
    }

    /*
     * 删除分类
     * */
    @ApiOperation(value = "删除分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "需要删除的分类id集合",dataTypeClass = Collections.class,paramType = "path"),
    })
    @DeleteMapping("/category/{id}")
    public ResponseResult<?> deleteCategory(@PathVariable("id") List<Long> ids) {
        return categoryService.deleteCategory(ids);
    }

    /*
     * 导出所有分类
     * */
    @ApiOperation(value = "导出分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "response", value = "响应http请求的对象",dataTypeClass = Object.class,paramType = "form"),
    })
    @GetMapping("/category/export")
    public void export(HttpServletResponse response) {
        try {
            // 设置下载文件的请求头
            WebUtils.setDownLoadHeader("分类.xlsx", response);
            //获取需要导出的数据
            List<Category> list = categoryService.list();
            List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(list, ExcelCategoryVo.class);
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出")
                    .doWrite(excelCategoryVos);
        } catch (IOException e) {
            ResponseResult<?> responseResult = new ResponseResult<>();
            WebUtils.renderString(response, JSON.toJSONString(responseResult.error(AppHttpCodeEnum.SYSTEM_ERROR.getCode(), AppHttpCodeEnum.SYSTEM_ERROR.getMsg())));
            e.printStackTrace();
        }
    }

    /*
     * 分页查询所有友链
     * */
    @ApiOperation(value = "分页查询友链列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页号",dataTypeClass = Integer.class,example = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页大小",dataTypeClass = Integer.class,example = "1"),
            @ApiImplicitParam(name = "name",value = "友链名称",dataTypeClass = String.class),
            @ApiImplicitParam(name = "status",value = "友链状态",dataTypeClass = String.class)
    })
    @GetMapping("/link/list")
    public ResponseResult<?> getLinkPage(Integer pageNum, Integer pageSize, String name, String status) {
        return linkService.getPage(pageNum, pageSize, name, status);
    }

    /*
     * 新增友链
     * */
    @ApiOperation(value = "新增友链")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "linkDto", value = "友链数据传输对象",dataTypeClass = Object.class),
    })
    @PostMapping("/link")
    public ResponseResult<?> addLink(@RequestBody LinkDto linkDto) {
        return linkService.addLink(linkDto);
    }

    /*
     * 修改友链，获取友链详情
     * */
    @ApiOperation(value = "根据友链id获取友链详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "友链id",dataTypeClass = Long.class,example = "1"),
    })
    @GetMapping("/link/{id}")
    public ResponseResult<?> getLinkById(@PathVariable("id") Long id) {
        return linkService.getDetails(id);
    }

    /*
     * 修改友链
     * */
    @ApiOperation(value = "修改友链")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "linkDto", value = "友链数据传输对象",dataTypeClass = Object.class),
    })
    @PutMapping("/link")
    public ResponseResult<?> updateLink(@RequestBody LinkDto linkDto) {
        if (!StringUtils.hasText(linkDto.getName())) {
            throw new SystemException(AppHttpCodeEnum.LINK_NAME_ISNULL);
        }
        if (!StringUtils.hasText(linkDto.getDescription())) {
            throw new SystemException(AppHttpCodeEnum.LINK_DESCRIPTION_ISNULL);
        }
        if (!StringUtils.hasText(linkDto.getLogo())) {
            throw new SystemException(AppHttpCodeEnum.LINK_LOGO_ISNULL);
        }
        if (!StringUtils.hasText(linkDto.getAddress())) {
            throw new SystemException(AppHttpCodeEnum.LINK_ADDRESS_ISNULL);
        }
        return linkService.updateLink(linkDto);
    }

    /*
     * 友链删除
     * */
    @ApiOperation(value = "删除友链")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "需要删除的友链的id集合",dataTypeClass = Collections.class,paramType = "path"),
    })
    @DeleteMapping("/link/{ids}")
    public ResponseResult<?> deleteLinkByIds(@PathVariable("ids") List<Long> ids) {
        return linkService.deleteLink(ids);
    }

    /*
     * 修改状态
     * */
    @ApiOperation(value = "修改友链状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "linkStatusDto", value = "友链状态数据传输对象",dataTypeClass = Object.class),
    })
    @PutMapping("/link/changeLinkStatus")
    public ResponseResult<?> changeLinkStatus(@RequestBody LinkStatusDto linkStatusDto) {
        linkService.update(new LambdaUpdateWrapper<Link>().eq(Link::getId, linkStatusDto.getId()).set(Link::getStatus, linkStatusDto.getStatus()));
        return ResponseResult.okResult();
    }

}
